var app = angular.module('breadTrip', []);
var hotel = {
    'not_book_hotel' :['我还没有预订酒店', '在您预订好酒店后，可以通过微信服务号或400电话与我们联系，以确认接送地点和时间。'],
    'stay_family' : ['我住在当地亲朋家', '在预订成功后，您可以通过微信服务号或400电话与我们联系，以确定您最方便的接送地点和时间。'],
    'no_hotel' : ['我的酒店不在列表中', '在预订成功后，您可以通过微信服务号或400电话与我们联系，以确认接送地点和时间。']
};
vAppSchema.setHotelName = function(hotelType, name){
    var $textarea = $('.textarea[name="'+hotelType+'"]'), 
        $title = $textarea.parents('tr').find('.title'),
        res = '',
        local_obj = JSON.parse(localStorage.getItem(BT.context('storageName')));
    if(hotel[name]){
        res = hotel[name][1];
        $title.text(hotel[name][0]).addClass('hotel-title');
        $.each(local_obj.extended, function(i, j){
            if(j.name_en == 'hotel_name'){
                j.title = hotel[name][0];
                j.value = res;
                $textarea.data('title', hotel[name][0]);
                localStorage[BT.context('storageName')] = JSON.stringify(local_obj);
            }
        });
    }else{
        res = name;
        $title.text($title.data('name')).removeClass('hotel-title');
        $.each(local_obj.extended, function(i, j){
            if(j.name_en == 'hotel_name'){
                delete j.title;
                j.value = res;
                $textarea.removeAttr('data-title');
                localStorage[BT.context('storageName')] = JSON.stringify(local_obj);
            }
        });
    }
    $textarea.text(res);
}
vAppSchema.setNewTime = function(timeType, sTime){
    $("input[name='"+ timeType +"']").val(sTime);
}
// 解决jinja2和angular的花括号{{}}冲突的方法
app.config(['$interpolateProvider', function($interpolateProvider) {
    $interpolateProvider.startSymbol('{[');
    $interpolateProvider.endSymbol(']}');
}]);
app.controller('orderController', ['$scope', function($scope){
    $scope.storageName = BT.context('storageName');

    var _obj, _initObj, localData;
    localData = getLocalStorage($scope.storageName);
    if(obj){
        if(obj.basic[0]){
            obj.basic.filter(function(item,index){
                item.filter(function(i, j){
                    if(i.name_en == 'price'){
                        i.price = i.value;
                    }
                })
            });
        }
        
        localStorage['_init_'+BT.context('productPK')] = JSON.stringify(obj.basic[0]);
        _initObj = obj.basic[0];
        if(getObj(obj, localData)){
            _obj = localData;
        }else{
            _obj = obj;
        }
    }else{
        _obj = localData;
        _initObj = getLocalStorage('_init_'+BT.context('productPK'));
    }
    
    $scope.isAddNew = _obj.is_add_product_type;
    $scope._initType = _initObj;
    // 动态数据
    $scope.res = {
        'is_add_product_type' : _obj.is_add_product_type,
        'is_baby' : _obj.is_baby || false,
        'has_baby' : _obj.has_baby || false,
        'basic' : _obj.basic,
        'contact' : _obj.contact,
        'extended' : _obj.extended,
        'detail' : _obj.agreement ? _obj.detail : true,
        'total_price' : _obj.total_price
    };

    /** 
    **  basic     ———— 产品基本信息
    **  contact             ————  联系人信息
    **  extended             ————  备注信息
    **  agreement         ————gi  接受协议
    **  total_price       ————  总价格
    
    **/ 
    function getObj(obj, localData){
        var flag = true;
        function compareObj(obj, local){
            var f = true;
           if(obj != local){
                if(obj && local &&  obj.length == local.length){
                    obj.filter(function(item, index){
                        if(item.name != local[index].name){
                            f = false;
                        }else{
                            if(item.name_en.match(/^custom_/)){
                                if(item.name_en != local[index].name_en){
                                    f = false;
                                }else{
                                    if(item.type == 'select'){
                                        if(item.value.length == local[index].value.length){
                                            item.value.filter(function(i, j){
                                                if(i.value != local[index].value[j].value) f = false;
                                            });
                                        }else{
                                            f = false;
                                        }   
                                    }
                                }
                            }
                        }
                    });
                }else if(obj && local &&  obj.length != local.length){
                    f = false;
                }
            }
            return f; 
        }
        if(localData){
            if(obj.is_add_product_type != localData.is_add_product_type){
                flag = false;
            }else{
                if(flag) flag = compareObj(obj.basic[0], localData.basic[0]);
                if(flag) flag = compareObj(obj.extended, localData.extended);
                if(flag) flag = compareObj(obj.contact, localData.contact);
            }
        }else{
            flag = false;
        }
        return flag;
    };

    // 数据写入 localStorage
    function setLocalStorage(name, callback){
        if($scope.res.extended){
            $scope.res.extended.filter(function(item, index){
                if(item.type != 'select'){
                    if(item.type == 'textarea'){
                        var $textarea = $('.textarea[name='+ item.name_en+']');
                        item.value = $textarea.text() || '';
                        $textarea.text(item.value);
                        if($textarea.data('title')){
                            item.title = $textarea.data('title');
                        }else{
                            delete item.title;
                        }
                    }else{
                        item.value = $('input[name='+ item.name_en+']').val() || '';
                    }
                }else{
                    var n = $('input[name='+ item.name_en+']').val();
                    item.value.filter(function(i, j){
                        if(n == i.value){
                            i.selected = true;
                        }else{
                            i.selected = false;
                        }
                    })
                }
            });
        }
        localStorage[name] = JSON.stringify($scope.res);     
        callback && callback();
    };
    // 获取 localStorage 数据
    function getLocalStorage(name){
        if(localStorage.getItem(name)){
            return JSON.parse(localStorage.getItem(name));   
        }  
    }
    // 获取 order_id,plan_id,device_id参数信息
    function getHrefSuffix(){
        var param = location.search.replace(/\?/, '').split('&'), 
            arr = [];
        param.filter(function(i){
            if(i.indexOf("plan_id") > -1 || i.indexOf("device_id") > -1 || i.indexOf("order_id") > -1){
                arr.push(i);
            }
        });
        return arr.join('&');
    }
    // 添加新购买类型
    $scope.addNewType = function(){
        $scope.res.basic.push($scope._initType);
        localStorage['new_basic'] = JSON.stringify($scope.res.basic);
        var local = getLocalStorage('new_basic');
        $scope.res.basic = local;
        getTotalPrice();  
    };
    // 跳转链接
    $scope.goHref = function(id, cate, url){ 
        setLocalStorage($scope.storageName);
        var href;
        if(id == 'rule'){
            href = location.origin + url + $scope.hrefSuffix;
        }else{
            var type_ids = [];
            $scope.res.basic.filter(function(i, j){
                if(typeof(id) == 'number'){
                    localStorage['type_'+ BT.context('productPK')] = id;
                    if(id == j){
                        i.filter(function(v, k){
                            if(v.name_en == 'pcategory'){
                                href = url + $scope.hrefSuffix + '&value='+ v.value;
                            } 
                        }); 
                    }
                }
                if(id == 'date'){
                    i.filter(function(v, k){
                        if(v.name_en == 'pcategory'){
                            type_ids.push(v.value);
                        } 
                    }); 
                }
            });
            if(id == 'date') href =  url + $scope.hrefSuffix + '&type_ids=' + type_ids.join(',');
        }
        location.href = href;
    };
    // 获取使用日期
    function getTravelDate(){
        var param = location.search.replace(/\?/, '').split('&');
        param.filter(function(i){
            if(i.indexOf('travel_date') > -1){
                var data = i.split('=');
                $scope.res.extended.filter(function(item, value){
                    if(item.type == 'url' && item.name_en == 'date'){
                        item.value = data[1];
                    }
                });
            }
        });
    };
    // 获取总价格
    function getTotalPrice(){
        var sum = 0, price=[];
        $scope.res.basic.filter(function(item, value){
            item.filter(function(i, v){
                if(i.name_en == 'price'){
                    price.push(i.price);
                }
            })
        });
        for(var i in price){
            sum += parseFloat(price[i]);
        }
        $scope.res.total_price = sum;
    };
    // 更改价格price
    function resetData(_index, _name, _val){
        $scope.res.basic.filter(function(item, value){
            if(_index == value){
                var n = [], s='';
                item.filter(function(i, j){
                    if(i.name_en == _name) i.value = _val;
                    if(i.name_en == 'count' || i.name_en == 'days') n.push(i.value);
                    if(i.name_en == 'price'){
                        s = i.value;
                        for(var k in n){
                            s *= parseInt(n[k]);
                        }
                        i.price = parseFloat(s);
                        getTotalPrice(); 
                    }
                });
            }
        });   
    };
    // 设置时间
    $scope.changeTime = function(name, value){
        setLocalStorage($scope.storageName);
        if ( typeof(android) != "undefined" ) {
            if(!BT.context('isBreadtrip')){
                var hour = -1,
                    minute = -1;
                if(value){
                    var data = value.split(':');
                    hour = parseInt(data[0]);
                    minute = parseInt(data[1]);
                }
                vAppSchema.showNewSetTimePicker(name, hour, minute);
            }
        }
    };
    $scope.showTime = function($event){
        $($event.target).attr('type', 'time');
    };
    $scope.timeblur = function($event){
        var val = $($event.target).val();
        if( val == '')  $($event.target).attr('type', 'text');
    };
    // 设置hotel
    $scope.setHotel = function(name){
        var UA = navigator.userAgent.toLowerCase();
        if(UA.match(/vacation/)){
            setLocalStorage($scope.storageName);
            vAppSchema.goBookingHotel(name);
        }
    };
    // input number 事件
    $scope.changeAmount = function($event){
        var _this = $($event.target),
            _index = _this.data('id'),
            _name = _this.attr('name'),
            _val = parseInt(Math.abs(_this.val()));
        _this.val(_val);
        if(_this.hasClass('re-price')){
            resetData(_index, _name, _val);
        } 
    };
    //  初始化
    $scope.init = function(){
        getTravelDate();
        getTotalPrice();
        $scope.$watch("res", function(){});
        $scope.hrefSuffix = '?' + getHrefSuffix();
    };
    // 提交表单
    $scope.submitForm = function(isValid){
        setLocalStorage($scope.storageName);
        if($('input[type="time"]').length> 0){
            $.each($('input[type="time"]'), function(i, j){
                var $j = $(j),
                   v = $j.val().split(':');
                $j.val(v[0]+':'+v[1]);
            });
        }
       
        if(!BT.context('UserIsAuthenticated') && BT.context('isBreadtrip')) {
            var url = location.origin + '/prodcuct/'+ BT.context('productPK')+'/order/';
            btAppSchema.jumpToLogin(url); 
            return false;
        } else{
            $scope.res.valid = true;
            if(isValid){
                HTMLFormElement.prototype.submit.call($('#form')[0]);
            }else{
                return false;
            }
        }
    };
    // 禁止enter减提交表单
    $scope.onKeyDown = function(e){
        if(e.which == 13){
            e.preventDefault();
            return false;
        }
    };
    $scope.goDetail = function(){
        var $btn = $('#detail-btn');
        if($btn.hasClass('push')) return;
        $btn.addClass('push');
        var name = BT.context('productName'),
            mtu_id = BT.context('productMtuId'),
            poi_id = BT.context('productPoiId');
        if($('body').data('version') != 'None'){
            vAppSchema.goPoiDetail(name, poi_id, false, '', mtu_id);
        }else{
            location.href = location.origin + '/share/product/' + BT.context('productPK') + '/book/';
        }
        
        setTimeout(function(){
            $btn.removeClass('push');
        }, 1000);
    };
    $scope.init();
}]);

app.directive('stringToNumber', function() {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(value) {
                return '' + value;
            });
            ngModel.$formatters.push(function(value) {
                return parseFloat(value, 10);
            });
        }
    };
});

app.directive('formatDate', function(){
    return {
        require: 'ngModel',
        link: function(scope, elem, attr, ngModelCtrl) {
            ngModelCtrl.$formatters.push(function(modelValue){
                if(modelValue) {
                    var t = modelValue.split(':');
                  return new Date(0,0,0, t[0], t[1], 0);
                }
            });
            ngModelCtrl.$parsers.push(function(value){
                var t = '';
                if(typeof(value) == 'object'){
                    t = value.toTimeString().split(':');
                }else{
                    t = value.split(':');
                }
                return t[0]+':'+t[1];
            });
        }
    };
});
$(function(){
    // 接送酒店箭头图标显示策略
    var UA = navigator.userAgent.toLowerCase();
    if(UA.match(/vacation/)){
        if($('.hotel_icon')){
            $('.hotel_icon').removeClass('hide').siblings('textarea').addClass('textarea-in-app');
        }
    }
});